-- init.lua
print('Setting up WIFI...')

wifi_ssd = "CMCC"
--wifi_ssd = "Azxc"
wifi_pwd = ""
wifi.setmode(wifi.STATION)
wifi.sta.config({ssid=wifi_ssd,pwd=wifi_pwd})
wifi.sta.connect()
wifitimer = tmr.create()

tState = 0 -- 当前加热状态

tStatePin = 3  -- 加热状态读取
tHeatPin = 4  -- 加热


-- -- 设置模拟按键引脚模式
gpio.mode(tHeatPin, gpio.OUTPUT)

-- 设置模拟按键引脚默认
gpio.write(tHeatPin,gpio.HIGH)

-- 模拟按键按下操作
function keyPress(pin)
  gpio.write(pin, gpio.LOW)
  tmr.delay(100000)  -- 100ms 按键动作
  gpio.write(pin, gpio.HIGH)
end

wifitimer:register(1000, tmr.ALARM_AUTO, function()
    if wifi.sta.getip() == nil then
        print('Waiting for IP ...')
    else
        print('IP is ' .. wifi.sta.getip())
        wifitimer:stop(1)
    end
end)
wifitimer:start()

-- Serving static files
dofile('httpServer.lua')
httpServer:listen(80)

-- Custom API

-- Get json
httpServer:use('/json', function(req, res)
    res:type('application/json')
    res:send('{"data": "test"}')
end)

httpServer:use('/heat', function(req, res)
    keyPress(tHeatPin)
    print("heat key press")
    res:type('application/json')
    res:send('{"heat": "success"}')
end)

httpServer:use('/state', function(req, res)
    gpio.mode(tStatePin, gpio.OUTPUT)
    gpio.write(tStatePin, gpio.LOW)
    tmr.delay(100)
    gpio.mode(tStatePin, gpio.INPUT)
    tState = gpio.read(tStatePin)
    res:type('application/json')
    res:send('{"heat_state": '..tState..'}')
end)
